package com.shenganyuan.smac.risk;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.oklib.utils.Logger.Logger;
import com.oklib.utils.network.http.ViseHttp;
import com.oklib.utils.network.http.callback.ACallback;
import com.oklib.utils.network.http.callback.UCallback;
import com.oklib.utils.view.SnackbarUtil;
import com.oklib.utils.view.ToastUtils;
import com.shenganyuan.smac.App;
import com.shenganyuan.smac.R;
import com.shenganyuan.smac.adapter.ImagePickerAdapter;
import com.shenganyuan.smac.common.BaseActivity;
import com.shenganyuan.smac.common.Config;
import com.shenganyuan.smac.common.beans.EventRefreshPage;
import com.shenganyuan.smac.common.beans.LocationInfo;
import com.shenganyuan.smac.common.beans.RiskResource;
import com.shenganyuan.smac.common.data.AnyPrefUtil;
import com.shenganyuan.smac.common.view.CommonSelectDialog;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.shenganyuan.smac.common.Config.PIC_COMPRESS_SIZE;

/**
 * 隐患信息录入
 *
 * @author Damon
 */

public class ActRiskInfoAdd extends BaseActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener {
    @BindView(R.id.common_toolbar_center_title)
    TextView commonToolbarCenterTitle;
    @BindView(R.id.action_save)
    TextView action_save;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.et_send)
    EditText etSend;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.progress)
    ProgressBar progress;
    //隐患信息
    @BindView(R.id.tv_check_position)
    TextView tvCheckPosition;
    @BindView(R.id.tv_risk_resource)
    TextView tvRiskResource;
    @BindView(R.id.tv_risk_type)
    TextView tvRiskType;
    @BindView(R.id.tv_risk_level)
    TextView tvRiskLevel;
    @BindView(R.id.tv_operation_method)
    TextView tvOperationMethod;

    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;

    private ImagePickerAdapter adapter;
    private ArrayList<ImageItem> selImageList; //当前选择的所有图片

    private RiskResource resource;

    @Override
    public int getLayoutId() {
        return R.layout.act_risk_info_add;
    }

    @Override
    public void initUI(Bundle savedInstanceState) {
        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(mContext, selImageList, Config.PIC_SIZE);
        adapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void initData() {
        setTitle("隐患信息录入");
        resource = (RiskResource) getIntent().getSerializableExtra("riskResource");
        pageData(resource);
    }

    /**
     * 页面数据
     *
     * @param data
     */
    private void pageData(RiskResource data) {
        if (data == null) {
            return;
        }
        tvCheckPosition.setText(data.getBsdx());
        tvRiskResource.setText(data.getBsnr());
        tvRiskType.setText(data.getSglx());
        tvRiskLevel.setText(data.getPjJb());
        tvOperationMethod.setText(data.getDxgzcs());
    }

    @OnClick({R.id.action_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.action_save:
                operateData();
                break;
        }
    }

    /**
     * 9.隐患信息保存
     * <p>
     * djuserid	是	String	用户ID，登录返回值djuser的ID
     * gkwxbsid	是	String	危险源ID
     * gkzydyid	是	String	风险点ID
     * yhnr	是	String	隐患内容 最大值100字内
     * gps	是	String	GPS坐标
     * picfile	是	String	照片名 如多文件上传文件名加序号
     * token	是	String	登录返回值access_token
     *
     * @return
     */
    private void operateData() {
        //危险源(危险标识)id
        String gkwxbsid = resource.getId();
        //风险点(作业单元)id
        String gkzydyid = getIntent().getStringExtra("gkzydyid");
        String nr = etSend.getText().toString().trim();

        if (TextUtils.isEmpty(gkwxbsid) || TextUtils.isEmpty(gkzydyid)) {
            SnackbarUtil.showShort(getWindow().getDecorView(), "信息不完整");
            return;
        }
        if (TextUtils.isEmpty(nr)) {
            SnackbarUtil.showShort(getWindow().getDecorView(), "内容不能为空");
            return;
        }
        if (selImageList == null || selImageList.size() <= 0) {
            SnackbarUtil.showShort(getWindow().getDecorView(), getResources().getString(R.string.str_msg_pic_must_one));
            return;
        }

        List<String> pathsToCompress = new ArrayList<>();
        if (selImageList != null) {
            for (int i = 0; i < selImageList.size(); i++) {
                String path = selImageList.get(i).path;
                pathsToCompress.add(path);
            }
        }
        progress.setVisibility(View.VISIBLE);
        List<String> pathsCompressResult = new ArrayList<>();

        Luban.with(this)
                .load(pathsToCompress)                                   // 传人要压缩的图片列表
                .ignoreBy(PIC_COMPRESS_SIZE)                                  // 忽略不压缩图片的大小
                .setTargetDir(Config.APP_CARD_PATH_PICTURE_COMPRESS)                        // 设置压缩后文件存储位置
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                        Logger.e("开始压缩");
                    }

                    @Override
                    public void onSuccess(File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
//                        Logger.e(file.getPath() + "   压缩成功");
                        pathsCompressResult.add(file.getPath());
                        //压缩完成
                        if (pathsCompressResult.size() == pathsToCompress.size()) {
                            toSave(pathsCompressResult);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                        progress.setVisibility(View.GONE);
                        SnackbarUtil.showShort(getWindow().getDecorView(), "文件压缩失败，请重试");
                    }
                }).launch();    //启动压缩

    }

    /**
     * 提交数据
     *
     * @param pathsCompressResult
     */
    private void toSave(List<String> pathsCompressResult) {
        //危险源(危险标识)id
        String gkwxbsid = resource.getId();
        //风险点(作业单元)id
        String gkzydyid = getIntent().getStringExtra("gkzydyid");
        String nr = etSend.getText().toString().trim();
        Map<String, String> req = new HashMap<>();
        req.put("djuserid", App.getCurrentUser().getId());
        req.put("gkwxbsid", gkwxbsid);
        req.put("gkzydyid", gkzydyid);
        req.put("yhnr", nr);
        String gps = "";
        LocationInfo locationInfo = AnyPrefUtil.getLocationInfo();
        if (locationInfo != null) {
            gps = locationInfo.longitude + ";" + locationInfo.latitude;
        }
        req.put("gps", gps);
        req.put("token", App.getAccessToken());
        req.put("dwxxId", App.getCurrentUser().getDwxxId());

        Map<String, File> files = new HashMap<>();
        for (int i = 0; i < pathsCompressResult.size(); i++) {
            String path = pathsCompressResult.get(i);
            files.put("picfile" + i, new File(path));
        }
        ViseHttp.UPLOAD("yhxxsave", new UCallback() {
            @Override
            public void onProgress(long currentLength, long totalLength, float percent) {
                if (percent == 100) {

                }
                progress.setProgress((int) percent);
                action_save.setClickable(false);
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                Logger.i("upload errorCode:" + errCode + ",errorMsg:" + errMsg);
            }
        }).addParams(req)
                .addFiles(files)
                .request(new ACallback<Object>() {
                    @Override
                    public void onSuccess(Object data) {
                        ToastUtils.showToast(mContext, "保存成功");
                        EventBus.getDefault().post(new EventRefreshPage(Config.EventKit.KEY_EVENT_REFRESH_ACTRISKRECORDS));
                        finish();
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        action_save.setClickable(true);
                        progress.setVisibility(View.GONE);
                        Logger.i("upload errorCode:" + errCode + ",errorMsg:" + errMsg);
                    }
                });
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                ArrayList<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                CommonSelectDialog selectDialog = CommonSelectDialog.newInstance(names);
                selectDialog.addOnSingleCheckListener(new CommonSelectDialog.OnSingleCheckListener() {
                    @Override
                    public void onSingleCheck(int position, String value) {
                        ToastUtils.showToast(mContext, value);
                        switch (position) {
                            case 0: // 直接调起相机
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(Config.PIC_SIZE - selImageList.size());
                                Intent intent = new Intent(mContext, ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, REQUEST_CODE_SELECT);
                                break;
                            case 1:
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(Config.PIC_SIZE - selImageList.size());
                                Intent intent1 = new Intent(mContext, ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                                break;
                            default:
                                break;
                        }
                    }
                });
                selectDialog.show(getSupportFragmentManager(), "choose_operation");
                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(mContext, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }

    ArrayList<ImageItem> images = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        }
    }
}
